package cn.enilu.itnews.controller;

import cn.enilu.flash.core.db.Pagination;
import cn.enilu.itnews.entity.News;
import cn.enilu.itnews.service.NewsService;
import com.google.common.base.Strings;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * class NewsController<br>
 * </p> Copyright by easecredit.com<br>
 * 作者: zhangtao <br>
 * 创建日期: 16-9-6<br>
 */

@Controller
@RequestMapping("/")
public class NewsController extends BaseController {
    @Inject
    private NewsService newsService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model) {
        Pagination<News> news = newsService.search(getQueryForm(request));
        News latest = newsService.getLatest();
        model.addAttribute("news", news);
        model.addAttribute("latest",latest);

        return "front/index";
    }
    @RequestMapping(value = "/submit",method = RequestMethod.GET)
    public String new0(){
        return "front/submit";
    }
    @RequestMapping(value = "/submit",method = RequestMethod.POST)
    public String create(HttpServletRequest request,
                         @Valid News news, BindingResult result, Model model,
                         RedirectAttributes redirectAttrs){
        if(Strings.isNullOrEmpty(news.getDescript())||news.getDescript().length()<20){
            return "redirect:/submit";
        }else{
            Map user = (Map) request.getSession().getAttribute("user");
            if(user!=null){
                news.setAuthor(Long.valueOf(user.get("id").toString()));
            }else{
                news.setAuthor(0L);
            }
            newsService.create(news);
        }
        return "redirect:/";
    }
}
